//
//  RegisterViewController.m
//  cm
//
//  Created by suyibaishan on 2017/11/1.
//  Copyright © 2017年 feihu. All rights reserved.
//

#import "RegisterViewController.h"
#import "ApproveViewController.h"
#import "ProtocolViewController.h"

@interface RegisterViewController () <UITextFieldDelegate>
{
    UIScrollView *_scrollView;
    UITextField *inviteField;
    UITextField *accountField;
    UITextField *verifyField;
    UITextField *password;
    UITextField *surePassword;
    UIView *fetchView;
    UILabel *fetchLabel;
    NSInteger timeLeft;
    NSTimer *timer;
    UIView *verifyView;
    UIButton *agreementBtn;
    BOOL moveUp;
}
@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createRegisterView];
    
    // 监听键盘弹起
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardDidHidden:) name:UIKeyboardDidHideNotification object:nil];
}

-(void)createRegisterView
{
    self.titleLabel.text = @"注册";
    self.backButton.hidden = NO;
    
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, self.baseBarHeight, kScreenWidth, kScreenHeight - self.baseBarHeight)];
    _scrollView.backgroundColor = [UIColor whiteColor];
    _scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_scrollView];
    UITapGestureRecognizer *scrollTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hidekeyBoard)];
    [_scrollView addGestureRecognizer:scrollTap];
    
    UIImageView *logoImage = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth - 150)/2, 20, 150, 80)];
    logoImage.image = [UIImage imageNamed:@"logo_login"];
    //    logoImage.backgroundColor = [UIColor redColor];
    [_scrollView addSubview:logoImage];
    
    UIView *accountView = [[UIView alloc] init];
    //    accountView.backgroundColor = [UIColor colorWithRed:0.2 green:0.21 blue:0.23 alpha:1];
    [_scrollView addSubview:accountView];
    accountView.sd_layout
    .leftSpaceToView(_scrollView, 40)
    .topSpaceToView(logoImage, 20)
    .widthIs(kScreenWidth - 80)
    .heightIs(45);
    
    UIImageView *accountImg = [[UIImageView alloc] initWithFrame:CGRectMake(15, 12.5, 14, 20)];
    accountImg.image = [UIImage imageNamed:@"phone"];
    //    accountImg.backgroundColor = [UIColor redColor];
    [accountView addSubview:accountImg];
    
    accountField = [[UITextField alloc] initWithFrame:CGRectMake(45, 0, kScreenWidth - 80, 45)];
    accountField.placeholder = @"请输入手机号码";
    [accountField setValue:[UIColor colorWithRed:0.66 green:0.68 blue:0.69 alpha:1] forKeyPath:@"_placeholderLabel.textColor"];
    accountField.delegate = self;
    //    accountField.textColor = [UIColor whiteColor];
    accountField.font = [UIFont systemFontOfSize:14];
    accountField.keyboardType = UIKeyboardTypeNumberPad;
    [accountView addSubview:accountField];
    
    verifyView = [[UIView alloc] init];
    //    verifyView.backgroundColor = [UIColor colorWithRed:0.2 green:0.21 blue:0.23 alpha:1];
    [_scrollView addSubview:verifyView];
    verifyView.sd_layout
    .leftSpaceToView(_scrollView, 40)
    .topSpaceToView(accountView, 0)
    .widthIs(kScreenWidth - 80)
    .heightIs(45);
    
    UIImageView *verifyImg = [[UIImageView alloc] initWithFrame:CGRectMake(15, 12.5, 14, 20)];
    verifyImg.image = [UIImage imageNamed:@"code"];
    //    verifyImg.backgroundColor = [UIColor redColor];
    [verifyView addSubview:verifyImg];
    
    verifyField = [[UITextField alloc] initWithFrame:CGRectMake(45, 0, kScreenWidth - 150, 45)];
    verifyField.placeholder = @"验证码";
    [verifyField setValue:[UIColor colorWithRed:0.66 green:0.68 blue:0.69 alpha:1] forKeyPath:@"_placeholderLabel.textColor"];
    verifyField.delegate = self;
    //    verifyField.textColor = [UIColor whiteColor];
    verifyField.font = [UIFont systemFontOfSize:14];
    verifyField.keyboardType = UIKeyboardTypeNumberPad;
    [verifyView addSubview:verifyField];
    
    fetchView = [[UIView alloc] init];
    [verifyView addSubview:fetchView];
    fetchView.sd_layout
    .rightSpaceToView(verifyView, 5)
    .topSpaceToView(verifyView, 2.5)
    .widthIs(80)
    .heightIs(45);
    UITapGestureRecognizer *fetchTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fetchButtonHandler)];
    [fetchView addGestureRecognizer:fetchTap];
    
    fetchLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80, 30)];
    fetchLabel.layer.cornerRadius = 15;
    fetchLabel.textColor = [UIColor whiteColor];
    fetchLabel.text = @"获取验证码";
    fetchLabel.textAlignment = NSTextAlignmentCenter;
    fetchLabel.font = [UIFont systemFontOfSize:13];
    fetchLabel.clipsToBounds = YES;
    fetchLabel.backgroundColor = [UIColor colorWithRed:0.67 green:0.81 blue:0.99 alpha:1];
    [fetchView addSubview:fetchLabel];
    
    UIView *passwordView = [[UIView alloc] init];
    //    passwordView.backgroundColor = [UIColor colorWithRed:0.2 green:0.21 blue:0.23 alpha:1];
    [_scrollView addSubview:passwordView];
    passwordView.sd_layout
    .leftSpaceToView(_scrollView, 40)
    .topSpaceToView(verifyView, 0)
    .widthIs(kScreenWidth - 80)
    .heightIs(45);
    
    UIImageView *passwordImg = [[UIImageView alloc] initWithFrame:CGRectMake(15, 12.5, 14, 20)];
    passwordImg.image = [UIImage imageNamed:@"password"];
    //    passwordImg.backgroundColor = [UIColor redColor];
    [passwordView addSubview:passwordImg];
    
    password = [[UITextField alloc] initWithFrame:CGRectMake(45, 0, kScreenWidth - 80, 45)];
    password.placeholder = @"设置密码";
    [password setValue:[UIColor colorWithRed:0.66 green:0.68 blue:0.69 alpha:1] forKeyPath:@"_placeholderLabel.textColor"];
    password.delegate = self;
    //    password.textColor = [UIColor whiteColor];
    password.font = [UIFont systemFontOfSize:14];
    password.secureTextEntry = YES;
    [passwordView addSubview:password];
    
    UIView *sureView = [[UIView alloc] init];
    //    sureView.backgroundColor = [UIColor colorWithRed:0.2 green:0.21 blue:0.23 alpha:1];
    //    nickNameView.layer.cornerRadius = 5;
    [_scrollView addSubview:sureView];
    sureView.sd_layout
    .leftSpaceToView(_scrollView, 40)
    .topSpaceToView(passwordView, 0)
    .widthIs(kScreenWidth - 80)
    .heightIs(45);
    
    UIImageView *sureImg = [[UIImageView alloc] initWithFrame:CGRectMake(15, 12.5, 14, 20)];
    sureImg.image = [UIImage imageNamed:@"password"];
    //    sureImg.backgroundColor = [UIColor redColor];
    [sureView addSubview:sureImg];
    
    surePassword = [[UITextField alloc] initWithFrame:CGRectMake(45, 0, kScreenWidth - 80, 45)];
    surePassword.placeholder = @"确认密码";
    [surePassword setValue:[UIColor colorWithRed:0.66 green:0.68 blue:0.69 alpha:1] forKeyPath:@"_placeholderLabel.textColor"];
    surePassword.delegate = self;
    //    surePassword.textColor = [UIColor whiteColor];
    surePassword.secureTextEntry = YES;
    surePassword.font = [UIFont systemFontOfSize:14];
    [sureView addSubview:surePassword];
    
    UIView *inviteView = [[UIView alloc] init];
    //    nameView.backgroundColor = [UIColor colorWithRed:0.2 green:0.21 blue:0.23 alpha:1];
    [_scrollView addSubview:inviteView];
    inviteView.sd_layout
    .leftSpaceToView(_scrollView, 40)
    .topSpaceToView(sureView, 0)
    .widthIs(kScreenWidth - 80)
    .heightIs(45);
    
    UIImageView *inviteViewImg = [[UIImageView alloc] initWithFrame:CGRectMake(15, 12.5, 14, 20)];
    inviteViewImg.image = [UIImage imageNamed:@"unlock"];
    //    nameViewImg.backgroundColor = [UIColor redColor];
    [inviteView addSubview:inviteViewImg];
    
    inviteField = [[UITextField alloc] initWithFrame:CGRectMake(45, 0, kScreenWidth - 80, 45)];
    inviteField.placeholder = @"请输入邀请人手机号码";
    [inviteField setValue:[UIColor colorWithRed:0.66 green:0.68 blue:0.69 alpha:1] forKeyPath:@"_placeholderLabel.textColor"];
    inviteField.delegate = self;
    //    nameField.textColor = [UIColor whiteColor];
    inviteField.font = [UIFont systemFontOfSize:14];
    inviteField.keyboardType = UIKeyboardTypeNumberPad;
    [inviteView addSubview:inviteField];
    
    for (NSInteger i = 0; i < 5; i++) {
        UIView *line = [[UIView alloc] init];
        line.backgroundColor = [UIColor colorWithRed:0.19 green:0.53 blue:0.98 alpha:1];
        [_scrollView addSubview:line];
        line.sd_layout
        .topSpaceToView(logoImage, 60+i*45)
        .leftSpaceToView(_scrollView, 80)
        .widthIs(kScreenWidth - 120)
        .heightIs(1);
    }
    
    agreementBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [agreementBtn setImage:[UIImage imageNamed:@"crook"] forState:UIControlStateSelected];
    [agreementBtn setImage:[UIImage imageNamed:@"uncrook"] forState:UIControlStateNormal];
    [agreementBtn addTarget:self action:@selector(agreementBtnHandler:) forControlEvents:UIControlEventTouchUpInside];
    [_scrollView addSubview:agreementBtn];
    agreementBtn.sd_layout
    .leftSpaceToView(_scrollView, (kScreenWidth - 183)/2)
    .topSpaceToView(inviteView, 12.5)
    .widthIs(15)
    .heightIs(15);
    agreementBtn.backgroundColor = [UIColor redColor];
    
    UILabel *agreementLabel = [[UILabel alloc] init];
    agreementLabel.font = [UIFont systemFontOfSize:12];
    agreementLabel.text = @"同意";
    agreementLabel.textColor = [UIColor colorWithRed:0.71 green:0.71 blue:0.71 alpha:1];
    [_scrollView addSubview:agreementLabel];
    agreementLabel.sd_layout
    .leftSpaceToView(agreementBtn, 3)
    .topSpaceToView(inviteView, 10)
    .widthIs(25)
    .heightIs(20);
    
    UIButton *termsBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [termsBtn setTitle:@"“车盟网络平台服务协议”" forState:UIControlStateNormal];
    [termsBtn setTitleColor:[UIColor colorWithRed:0.19 green:0.53 blue:0.98 alpha:1] forState:UIControlStateNormal];
    termsBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [termsBtn addTarget:self action:@selector(termsBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [_scrollView addSubview:termsBtn];
    termsBtn.sd_layout
    .leftSpaceToView(agreementLabel, 0)
    .topSpaceToView(inviteView, 10)
    .widthIs(140)
    .heightIs(20);

    UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    confirmBtn.backgroundColor = [UIColor colorWithRed:0.19 green:0.53 blue:0.98 alpha:1];
    [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [confirmBtn setTitle:@"注册" forState:UIControlStateNormal];
    confirmBtn.titleLabel.font = [UIFont boldSystemFontOfSize:15];
    confirmBtn.layer.cornerRadius = 20;
    [confirmBtn addTarget:self action:@selector(confirmBtnHandler) forControlEvents:UIControlEventTouchUpInside];
    [_scrollView addSubview:confirmBtn];
    confirmBtn.sd_layout
    .leftSpaceToView(_scrollView, 40)
    .topSpaceToView(inviteView, 55)
    .widthIs(kScreenWidth - 80)
    .heightIs(40);
    
    UILabel *answerLabel = [[UILabel alloc] init];
    answerLabel.font = [UIFont systemFontOfSize:13];
    answerLabel.textAlignment = NSTextAlignmentRight;
    answerLabel.text = @"已有账号?";
    answerLabel.textColor = [UIColor colorWithRed:0.71 green:0.71 blue:0.71 alpha:1];
    [_scrollView addSubview:answerLabel];
    answerLabel.sd_layout
    .leftSpaceToView(_scrollView, (kScreenWidth - 100)/2)
    .topSpaceToView(confirmBtn, 10)
    .widthIs(70)
    .heightIs(20);
    
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [loginBtn setTitleColor:[UIColor colorWithRed:0.19 green:0.53 blue:0.98 alpha:1] forState:UIControlStateNormal];
    loginBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [loginBtn addTarget:self action:@selector(loginBtnHandler) forControlEvents:UIControlEventTouchUpInside];
    [loginBtn setTitle:@"登陆" forState:UIControlStateNormal];
    [_scrollView addSubview:loginBtn];
    loginBtn.sd_layout
    .leftSpaceToView(answerLabel, 0)
    .topSpaceToView(confirmBtn, 10)
    .widthIs(30)
    .heightIs(20);
    
    [_scrollView setupAutoContentSizeWithBottomView:confirmBtn bottomMargin:50];
}

-(void)loginBtnHandler
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)keyboardWillShow:(NSNotification *)notification
{
    NSDictionary *info = [notification userInfo];
    CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    //    NSLog(@"keyboard changed, keyboard width = %f, height = %f",  kbSize.width, kbSize.height);
    
    // 在这里调整UI位置
    CGPoint pt = [surePassword convertPoint:CGPointMake(0, 0) toView:[UIApplication sharedApplication].keyWindow];
    float distanceToBottom = kScreenHeight - pt.y - surePassword.frame.size.height;  // 距离底部多远
    if( distanceToBottom >= keyboardSize.height )  // 键盘不会覆盖
        return;
    
    _scrollView.contentSize = CGSizeMake(_scrollView.contentSize.width, _scrollView.contentSize.height + keyboardSize.height); //原始滑动距离增加键盘高度
    
    // 差多少
    float offsetY = distanceToBottom - keyboardSize.height - 80;  // 补一些给各种输入法
    [_scrollView setContentOffset:CGPointMake(0, _scrollView.contentOffset.y - offsetY) animated:YES];
}

-(void)keyBoardDidHidden:(NSNotification *)notification
{
    //获取键盘高度
    NSValue *value = [[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    
    CGRect scrollViewFrame = _scrollView.frame;
    scrollViewFrame.size.height = _scrollView.bounds.size.height + keyboardSize.height;
    _scrollView.frame = scrollViewFrame;
}

-(void)hidekeyBoard
{
    [self.view endEditing:YES];
}

-(void)termsBtnAction
{
    ProtocolViewController *protocolVC = [[ProtocolViewController alloc] init];
    [self.navigationController pushViewController:protocolVC animated:YES];
}

-(void)agreementBtnHandler:(UIButton *)button
{
    if (button.selected == YES) {
        button.selected = NO;
    }
    else
    {
        button.selected = YES;
    }
}

-(void)fetchButtonHandler
{
    if ([accountField.text isEqualToString:@""]) {
        [self showMessage:@"请先输入手机号码"];
        return;
    }
    [[ToolNet sharedManager] getVerifyCode:accountField.text type:1 url:MMobileSms completionHandler:^(NSURLSessionDataTask *task, NSDictionary *responseJson, NSError *error) {
        if ([responseJson[@"code"] isEqual:@1]) {
            timeLeft = 60;
            [self startTimer];
            fetchView.userInteractionEnabled = NO;
        }
        else {
            [self showMessage:responseJson[@"msg"]];
        }
    }];
}

#pragma mark -- verifyCodeTime methods
-(void) onTimer
{
    if (timeLeft < 1) {
        [self stopTimer];
        fetchLabel.text = @"重新获取";
        fetchView.userInteractionEnabled = YES;
    }
    else{
        fetchLabel.text = [NSString stringWithFormat:@"%lds后重发", (long)timeLeft-1];
    }
    timeLeft--;
}

-(void) startTimer
{
    if (!timer) {
        timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
        fetchLabel.text = [NSString stringWithFormat:@"%lds后重发", (long)timeLeft];
    }
}

-(void) stopTimer
{
    if (timer) {
        [timer invalidate];
        timer = nil;
    }
}

-(void)confirmBtnHandler
{
    [self.view endEditing:YES];
    if ([password.text isEqualToString:@""]) {
        [self showMessage:@"亲，您还未填写您的密码哦！"];
        return;
    }
    if (agreementBtn.selected == NO) {
        [self showMessage:@"您需要先勾选同意服务协议才能注册"];
        return;
    }
//    const char *value = [password.text UTF8String];
//    unsigned char digest[CC_MD5_DIGEST_LENGTH];
//    CC_MD5(value, (unsigned)password.text.length, digest);
//    NSMutableString *passwordMD5 = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
//    for(NSInteger i = 0; i < CC_MD5_DIGEST_LENGTH; i++){
//        [passwordMD5 appendFormat:@"%02X", digest[i]];
//    }
    [[ToolNet sharedManager] registerApp:accountField.text password:surePassword.text vaidCode:verifyField.text refereeMobile:inviteField.text url:MRegCheck completionHandler:^(NSURLSessionDataTask *task, NSDictionary *responseJson, NSError *error) {
        if ([responseJson[@"code"] isEqual:@1]) {
            [mUserDefaults setObject:accountField.text forKey:@"account"];
            [mUserDefaults setObject:surePassword.text forKey:@"password"];
            [mUserDefaults synchronize];
            ApproveViewController *approveVC = [[ApproveViewController alloc] init];
            approveVC.userCode = responseJson[@"data"][@"userCode"];
            approveVC.account = accountField.text;
            [self.navigationController pushViewController:approveVC animated:YES];
        }
        else {
            [self showMessage:responseJson[@"msg"]];
        }
    }];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

#pragma - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    //    if (textField == password || textField == surePassword) {
    //        if (!moveUp) {
    //            moveUp = YES;
    //            [UIView animateWithDuration:0.2f animations:^{
    //                self.view.center = CGPointMake(self.view.center.x, self.view.center.y - 180);
    //            }completion:^(BOOL finished) {
    //
    //            }];
    //        }
    //        else
    //        {
    //            [UIView animateWithDuration:0.2f animations:^{
    //                self.view.center = CGPointMake(self.view.center.x, self.view.center.y - 180);
    //            }completion:^(BOOL finished) {
    //
    //            }];
    //        }
    //    }
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField;
{
    [textField resignFirstResponder];
    //    if (textField == password || textField == surePassword) {
    //        if (moveUp) {
    //            moveUp = NO;
    //            [UIView animateWithDuration:0.2f animations:^{
    //                self.view.center = CGPointMake(self.view.center.x, self.view.center.y + 180);
    //            } completion:^(BOOL finished) {
    //
    //            }];
    //        }
    //        else
    //        {
    //            [UIView animateWithDuration:0.2f animations:^{
    //                self.view.center = CGPointMake(self.view.center.x, self.view.center.y + 180);
    //            } completion:^(BOOL finished) {
    //
    //            }];
    //        }
    //    }
    return YES;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
